package com.keter.framework.web.component.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *  框架自定义的ErrorController：
 *  替代Spring默认的Whitelabel Error Page实现
 */
@RestController
@RequestMapping(value = "error")
public class ErrorController extends AbstractErrorController {
    private static final Logger logger = LoggerFactory.getLogger(ErrorController.class);

    public ErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @Override
    public String getErrorPath() {
        return "error";
    }

    @RequestMapping
    public String error(HttpServletRequest request, HttpServletResponse response) {
        Map err = this.getErrorAttributes(request,false);
        logger.info("出错了： path={},error={},message={}", err.get("path"),err.get("error"),err.get("message"));
        if(this.getStatus(request).equals(HttpStatus.NOT_FOUND)){
            return "请求的资源"+err.get("path")+"不存在！";
        }
        return getErrorPath();
    }
}